<?php

namespace iBrand\Shop\Server\Controllers\V2;

use iBrand\Common\Controllers\Controller;
use iBrand\Shop\Core\Repositories\CashRecordRepository;
use iBrand\Shop\Server\Resources\CashRecordResource;
use Illuminate\Http\Request;
use Validator;

class CashRecordController extends Controller
{
    protected $cashRecordRepository;

    public function __construct(CashRecordRepository $cashRecordRepository)
    {
        $this->cashRecordRepository = $cashRecordRepository;
    }

    public function store(Request $request)
    {
        $input = $request->except('_token', 'file');
        $rules = [
            'amount' => 'required|numeric',
            'category' => 'required',
        ];
        $message = [
            "required" => ":attribute 不能为空",
            "numeric" => ":attribute 只能是数字",
        ];
        $attributes = [
            'amount' => '收支金额',
            'category' => '项目类型',
        ];

        $validator = Validator::make($input, $rules, $message, $attributes);
        if ($validator->fails()) {

            return $this->failed($validator->messages()->first());
        }

        $clerk = auth('clerk')->user();

        $record = $this->cashRecordRepository->create([
            'clerk_id' => $clerk->id,
            'shop_id' => $clerk->shop_id,
            'amount' => $input['amount'] * 100,
            'category' => $input['category'],
            'remark' => $input['remark'] ? $input['remark'] : '',
        ]);

        return $this->success($record);
    }

    public function list()
    {
        $limit = request('limit') ? request('limit') : 15;
        $clerk = auth('clerk')->user();

        $where['shop_id'] = $clerk->shop_id;
        $where['created_at'] = ['>=', date('Y-m') . '-01 00:00:00'];
        $time['created_at'] = ['<=', date('Y-m') . '-' . date('t') . ' 23::59:59'];
        if (request('time')) {
            $where['created_at'] = ['>=', request('time') . '-01 00:00:00'];
            $time['created_at'] = ['<=', request('time') . '-' . date('t', strtotime(request('time'))) . ' 23::59:59'];
        }

        $list = $this->cashRecordRepository->getCashRecordPaginate($where, $time, $limit);

        $income = $list->where('amount', '>', 0)->sum('amount');
        $outcome = $list->where('amount', '<', 0)->sum('amount');
        $diff = $income + $outcome;

        return $this->paginator($list, CashRecordResource::class, ['income' => number_format($income, 2, '.', ''), 'outcome' => number_format($outcome, 2, '.', ''), 'diff' => number_format($diff, 2, '.', '')]);
    }
}